// pages/science/science.js
import { request } from '../../request/index.js'
Page({
  data: {
    activeKey: 0,
    varietys: [
      {id: 1, variety: '猫咪'},
    ],
    categorys: [
      {id: 1, category: '奶牛猫', pic: 'https://img.yzcdn.cn/vant/cat.jpeg'},
    ],
    search: '',
    show: false,
  },
  onLoad() {
    this.loadVarietys();
    this.loadCategorys(this.data.varietys[0].id)
  },
  onChange(event) {
    // 获取当前选中的索引
    const index = event.detail;
    // 根据索引获取当前选中的项
    const variety = this.data.varietys[index];
    this.loadCategorys(variety.id)
  },
  onChangeSerarch(e){
    this.setData({
      search: e.detail,
    });
  },
  onSearch() {
    const token = wx.getStorageSync('token');
    const that = this;
    request({
      url: '/variety/searchList?search='+that.data.search,
      method: 'GET',
      header: {
        'author': token ? token : '',
        'content-type': 'application/x-www-form-urlencoded' // 设置请求头为表单数据格式
      }
    }).then(res => {
      if (res.code === 0){
        const newData = res.data;
        console.log(newData);
        that.setData({ 
          categorys: newData, 
          show: newData.length === 0 ? true : false,
         });
      } else {
        wx.showToast({
          title: '错误',
          icon: 'error'
        })
      }
    })
  },
  loadVarietys() {
    const token = wx.getStorageSync('token');
    const that = this;
    request({
      url: '/variety/list',
      method: 'GET',
      header: {
        'author': token ? token : '',
      }
    }).then(res => {
      if (res.code === 0){
        const newData = res.data;
        that.setData({ varietys: newData });
      } else {
        wx.showToast({
          title: '错误',
          icon: 'error'
        })
      }
    })
  },
  loadCategorys(id) {
    const token = wx.getStorageSync('token');
    const that = this;
    let data = {
      id: id
    }
    request({
      url: '/variety/subList',
      method: 'GET',
      data: data,
      header: {
        'author': token ? token : '',
        'content-type': 'application/x-www-form-urlencoded' // 设置请求头为表单数据格式
      }
    }).then(res => {
      if (res.code === 0){
        const newData = res.data;
        that.setData({ categorys: newData });
      } else {
        wx.showToast({
          title: '错误',
          icon: 'error'
        })
      }
    })
  },
})